package com.test.daily.leetcode.y2021.m10.day1028;

import java.util.ArrayList;
import java.util.List;

/**
 * @descriptions: reorderedPowerOf2
 * @author: Tom
 * @date: 2021/10/28 下午 04:00
 * @version: 1.0
 */
public class ReorderedPowerOf2 {
    public static void main(String[] args) {
        ReorderedPowerOf2 rp02 = new ReorderedPowerOf2();
        for(int i = 1; i <= 100; i++){
            System.out.println(i + ":" + rp02.reorderedPowerOf2(i));
        }
    }

    public boolean reorderedPowerOf2(int n) {
        StringBuffer s = new StringBuffer(Integer.toString(n));
        List<String> list = new ArrayList<>();
        process(s, 0, list);
        for (String ans : list) {
            int num = Integer.parseInt(ans);
            if(((num - 1) & num) == 0){
                return true;
            }
        }
        return false;
    }

    public void process(StringBuffer s, int index, List<String> list) {
        if (index == s.length() - 1) {
            if (s.charAt(0) != '0') {
                list.add(s.toString());
            }
            return;
        }
        boolean[] isVisited = new boolean[10];
        for (int i = index; i < s.length(); i++) {
            if (!isVisited[s.charAt(i) - '0']) {
                swap(s, index, i);
                process(s, index + 1, list);
                isVisited[s.charAt(i) - '0'] = true;
                swap(s, index, i);
            }
        }
    }

    public void swap(StringBuffer s, int i, int j) {
        char tmp = s.charAt(i);
        s.setCharAt(i, s.charAt(j));
        s.setCharAt(j, tmp);
    }
}
